package com.xiaobai.customer.config;

import com.xiaobai.customer.exception.BusinessFeignException;
import com.xiaobai.customer.exception.TipException;
import com.xiaobai.customer.response.ResponseResult;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class FeignDecoder implements Decoder {

    private final SpringDecoder decoder;

    public FeignDecoder(SpringDecoder decoder) {
        this.decoder = decoder;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException {
        Method method = response.request().requestTemplate().methodMetadata().method();
        ResponseResult<?> decode;
        // 如果不是这个类型的，构造成这种类型
        if (method.getReturnType() != ResponseResult.class) {
            Type newType = new ParameterizedType() {
                @Override
                public Type[] getActualTypeArguments() {
                    return new Type[]{type};
                }

                @Override
                public Type getRawType() {
                    return ResponseResult.class;
                }

                @Override
                public Type getOwnerType() {
                    return null;
                }
            };
            decode = (ResponseResult<?>) this.decoder.decode(response, newType);
        } else {
            decode = (ResponseResult<?>) this.decoder.decode(response, type);
        }
        if (decode.getCode() != 200) {
           throw new BusinessFeignException(response.status(), decode.getCode(), decode.getMsg());
        }
        return decode.getData();
    }
}
